import { Injectable } from '@angular/core';

import { Http, Headers, Response, RequestOptions } from '@angular/http';

// import 'rxjs/add/operator/toPromise';
import { User, adminUser } from '../domain/user';
import { ApiService } from './api.service';
import { postUser } from "../domain/user";
import { changeHoliday } from '../domain/user'
import { registerUserModel } from "../domain/user";
// import {CookieService} from 'angular2-cookie/core';

@Injectable()
export class UserService {

  private api_url : string ;
  private headers : Headers ;

  public sharedUser: User;

  private cookie: string;

  constructor(private http: Http, private apiService: ApiService) {
      this.api_url = apiService.getUrl() + 'users/';
      this.headers = apiService.getHeaders();
      // this.cookie = this.cookieServ.get('cookie');
  }

  //查询所有User
  getUsers(): Promise<User[]> {
    const url = `${this.api_url}`;
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as User[])
      .catch(this.handleError);
  }

  //按id查询User
  getUserById(id: number): Promise<User> {
    const url = `${this.api_url}/${id}`;
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as User)
      .catch(this.handleError);
  }

  //按username查询User
  getUserByUsername(username: string): Promise<User> {
    const url = `${this.api_url}/?username=${username}`;
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => {
        let users = res.json() as User[];
        return (users.length > 0) ? users[0] : null;
      })
      .catch(this.handleError);
  }

  //创建一个User
  createUser(user: User): Promise<User> {
    const url = `${this.api_url}`;
    return this.http
      .post(url, JSON.stringify(user), { headers: this.headers })
      .toPromise()
      .then(res => res.json() as User)
      .catch(this.handleError);
  }

  //修改某个User
  updateUser(user: User): Promise<User> {
    const url = `${this.api_url}/${user.id}`;
    return this.http
      .put(url, JSON.stringify(user), { headers: this.headers })
      .toPromise()
      .then(() => user)
      .catch(this.handleError);
  }

  //删除某个User
  deleteUser(user: User): Promise<void> {
    const url = `${this.api_url}/${user.id}`;
    return this.http.delete(url, { headers: this.headers })
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  staffLogInService(user: postUser): Promise<User> {
    const url = `${this.api_url}`+'login/';
    let options = new RequestOptions({headers: this.headers, withCredentials: true})
    options.body = JSON.stringify(user);
    return this.http
      .post(url, JSON.stringify(user),options)
      .toPromise()
      .then(res => {
        console.log(res.headers)
        return res.json() as User
      })
      .catch(this.handleError);
  }

  getyearsHoliday() {
    const url = `${this.api_url}`+'departments/';
    let options = new RequestOptions({headers: this.headers, withCredentials: true})
    return this.http
      .get(url)
      .toPromise()
      .then(res => {
        return res.json() as adminUser
      })
      .catch(this.handleError_2)
  }

  setYearHoliday(model: changeHoliday) {
    const url = `${this.api_url}`+ 'annualLeaves/';
    let options = new RequestOptions({headers: this.headers, withCredentials: true})
    return this.http
      .post(url, JSON.stringify(model))
      .toPromise()
      .then ( () => {})
      .catch(this.handleError_2)

  }

  registerUser(registerUserModel: registerUserModel) {
    const url = `${this.api_url}` + 'register/';
    return this.http
      .post(url, JSON.stringify(registerUserModel))
      .toPromise()
      .then(() => {})
      .catch(this.handleError_3)
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    alert("用户名或密码错误❌");
    return Promise.reject(error.message || error);
  }

  private handleError_2(error: any): Promise<any> {
    console.error('An error occurred', error);
    alert("发生了错误❌");
    return Promise.reject(error.message || error);
  }

  private handleError_3(error: any): Promise<any> {
    console.error('An error occurred', error);
    alert("❌此 ID 已存在！");
    return Promise.reject(error.message || error);
  }
}